﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Interop;
using System.Windows.Threading;
using System.Threading;
using System.Reflection;
using FinPlusDBConn;
using FinPlusCommon;
using Messaging2;
using log = Logger.Logger;
using u = FinPlusUtility.Utility;

namespace FinPlusWPFControls
{
    public partial class FinPlusTabItem : TabItem, IFinPlusComponent
    {
        public string Id { get { return _id == null ? "ItemTab" : _id; } set { _id = value; } }
        public string[] States { get { return new string[] {  }; } }
        public string[] TestStates { get { return new string[] {  }; } }
        public IFinPlusFunctions Model { get { return _app.Model; } }
        public string ModelTest { get { return Model.ToString(); } }
        public bool IsValid { get; set; }

        private const string XmlNode = "root/current";
        private enum DockControls { FinPlusControl, Default }
        private FinPlusControl _app;
        private IFinPlusFunction _func;
        private string _id;
        private readonly string _user, _configPath, _name;

        public event EventHandler TabClosed;

        //construct
        public FinPlusTabItem(string configPath, string name)
        {
            InitializeComponent();
            _id = _name = name;
            _configPath = configPath;
            _user = Environment.UserName;
            Cursor = ((TextBlock)this.Resources["CPoint"]).Cursor;
        }

        //common control interface
        public void Dock(object control, string dock) 
        {
            IsValid = false;
            throw new NotImplementedException();
        }

        public void Initialise()
        { 
        
        }

        public void CommandRouter(IFinPlusFunction func)
        {
            try
            {
                if (_app != null)
                    _app.CaptureCommand(func);

                switch ((Commands)Enum.Parse(typeof(Commands), func.Name, true))
                {
                    case Commands.Open: Open(); break;
                    case Commands.Save: Save(); break;
                    case Commands.Close: Close(); break;
                    default: throw new Exception(string.Format("event not recognised {0}", func.Name));
                }
            }
            catch (Exception e)
            {
               IsValid = log.Log(Logger.Level.Error, e.Message, e);
            }
        }

        public void Dispose()
        {
            if (_app != null)
                _app.Dispose();
        }

        //public
        public void ShowButtons(bool show)
        {
            controlButtons.Visibility = show ? Visibility.Visible: Visibility.Collapsed;
        }

        //private
        private void Open()
        {
            try
            {
                u.Env env;
                var config = u.ConfigXml(_configPath + ".config", out env);
                Content = _app = new FinPlusApplication(_configPath, titleText.Text = _name, string.Empty, env);

                _func = new Function("FinPlusTabItem", "finPlusTabItem", Environment.UserName) { Object = finPlusTabItem };
                FinPlusAssembler.InjectState(_func, new Functions(_configPath + "web.state", XmlNode));
            }
            catch (Exception e)
            {
                log.Log(Logger.Level.Warning, e.Message, e);
            }
        }

        private bool Save()
        {
            var funcsState = FinPlusAssembler.ExtractState(_func, Environment.UserName);
            funcsState.ToXmlDoc(XmlNode).Save(_configPath + "web.state");
            return true;
        }

        private void Close()
        {
            try
            {
                if (TabClosed != null)
                    TabClosed.Invoke(Id, new EventArgs());

                Dispose();
            }
            catch (Exception e)
            {
                log.Log(Logger.Level.Error, Id, Id, e.Message, e);
            }
        }

        //cmds
        private enum Commands { Open, Save, Close }

        //events
        private void Tab_OnClose(object sender, RoutedEventArgs a) { CommandRouter(new Function(Commands.Close.ToString(), Id, _user)); }
        private void Tab_OnSave(object sender, RoutedEventArgs a) { CommandRouter(new Function(Commands.Save.ToString(), Id, _user)); }
        private void Tab_OnLoad(object sender, RoutedEventArgs a) { CommandRouter(new Function(Commands.Open.ToString(), Id, _user)); }
        private void Key_Click(object sender, KeyEventArgs a) { if (a.Key == Key.S && Keyboard.Modifiers == ModifierKeys.Control) Tab_OnSave(sender, a); }
     }
}
